package utils.common;

/**
 * Created by franklin on 6/5/2017.
 */

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.CoreConnectionPNames;
import utils.Logger.LoggerUtils;

import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;


/**
 *
 */
public class HttpManager {

    /**
     * 模拟各种Http请求
     * @param req
     * @return
     */
    @SuppressWarnings("deprecation")
    public static Map<String,Object> request(HttpRequest req){

        Map<String,Object> map = new HashMap<String,Object>();
        double begin = System.currentTimeMillis();
//        String type = req.getType();
        String type = req.getRequestLine().getMethod();
//        String url  = req.getUrl();
        String url = req.getRequestLine().getUri();

        //  抽象类HttpRequestBase实现了接口HttpUriRequest。
        HttpUriRequest method2 = null;
        HttpRequestBase method = null;
        org.apache.http.client.methods.HttpRequestBase httpReq;

        try {
            //匹配请求
            if("Post".equals(type)){
//                method = new PostMethod(url);
                method = new HttpPost(url);
            }else if("Get".equals(type)){
//                method = new GetMethod(url);
                method = new HttpGet(url);
            }else if("Delete".equals(type)){
//                method = new DeleteMethod(url);
                method = new HttpDelete(url);
            }else if("Put".equals(type)){
//                method = new PutMethod(url);
                method = new HttpPut(url);
            }else if("Trace".equals(type)){
//                method = new TraceMethod(url);
                method = new HttpTrace(url);
            }else if("Head".equals(type)){
//                method = new HeadMethod(url);
                method = new HttpHead(url);
            }else if("Options".equals(type)){
//                method = new OptionsMethod(url);
                method = new HttpOptions(url);
            }

//            HttpClient client = new HttpClient();
            HttpClient client2 = new DefaultHttpClient();
            HttpPost client = new HttpPost();

            //请求超时
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 556000);
            //读取超时
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 555000);
//            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
//            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            method.setHeader("Connection","close");
            method.setHeader("Referer",
                    "http://www.sojson.com");
            method.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0");

            //设置参数
//            String[] keys = req.getKeys(),values = req.getValues();
//            if(StringUtils.isNotBlank(keys,values)){
//                NameValuePair[] params = new NameValuePair[keys.length];
//                for (int i = 0; i < keys.length; i++) {
//                    params[i] = new NameValuePair(keys[i], values[i]);
//                }
////                method.setQueryString(params);
//                (HttpGet)method.setConfig(params);
//            }


            //设置请求头 和上面方法一致，如果一样，那么就覆盖。
            Header[] headKeys = req.getAllHeaders();
//            String[] headValues = req.getRequestLine().getUri();
            for (int i = 0;StringUtils.isNotBlank(headKeys.toString()) && i < headKeys.length; i++) {
//                method.setRequestHeader(headKeys[i], headValues[i]);
                method.setHeader(headKeys[i].toString(), req.getHeaders(headKeys[i].toString()).toString());
            }

//            int status = client.executeMethod(method);
            int status = client2.execute(new HttpHost(url), req).getStatusLine().getStatusCode();
            map.put("status",status);

//            Header[] heads = method.getResponseHeaders();
            Header[] heads = method.getAllHeaders();
            //获取请求的Host，用于IP解析
//            String host = method.getHostConfiguration().getHost();
            String host = method.getURI().getHost();

            StringBuffer sb = new StringBuffer("");
            for (Header header : heads) {
                sb.append(header.getName())
                        .append(" : ")
                        .append(header.getValue())
                        .append("\r\n");
            }
            //头信息
            map.put("head", sb.toString());
//            String result = method.getResponseBodyAsString();
            String result = method.getRequestLine().toString();
            map.put("result", result);
            String ip = "未知";
            try {
                InetAddress iAddress=InetAddress.getByName(host);
                ip = iAddress.getHostAddress();
                map.put("host", ip);
            } catch (Exception e) {
                LoggerUtils.fmtError(HttpManager.class, e, "获取IP地址失败，域名:[%s]", host);
            }
        } catch (UnknownHostException e) {
            //域名错误
            map.put("message", "请输入正确的网址");
            LoggerUtils.fmtError(HttpManager.class, e, "网址异常[%s]", url);
        } catch (SocketTimeoutException e) {
            //超时
            map.put("message", "请求地址超时");
            LoggerUtils.fmtError(HttpManager.class, e, "请求地址超时[%s]", url);
        } catch (Exception e) {
            //其他异常
            map.put("message", "请求出现未知异常，请重试！");
            LoggerUtils.fmtError(HttpManager.class, e, "请求出现未知异常，请重试！[%s]", url);
        }

        double end = System.currentTimeMillis();
        map.put("time", (end - begin) / 1000);
        return map;

    }


    public void httpClientUtils (){

        String method = null;
        Header[] headers = null;

        //  HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //  POST
        HttpPost httpPost = new HttpPost();
        method = httpPost.getMethod();
        headers = httpPost.getAllHeaders();

        //  GET
        HttpGet httpGet = new HttpGet();
        method = httpGet.getMethod();
        headers = httpGet.getAllHeaders();

        //  PUT
        HttpPut httpPut = new HttpPut();
        method = httpPut.getMethod();
        headers = httpPut.getAllHeaders();
    }


}
